<?php
// +----------------------------------------------------------------------
// | CoreThink [ Simple Efficient Excellent ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.corethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: jry <598821125@qq.com> <http://www.corethink.cn>
// +----------------------------------------------------------------------
namespace Admin\Controller;
use Think\Controller;
/**
 * 后台用户控制器
 * @author jry <598821125@qq.com>
 */
class UserController extends AdminController{
    /**
     * 用户列表
     * @author jry <598821125@qq.com>
     */
    public function index(){
        //搜索
        $keyword = I('keyword', '', 'string');
        $condition = array('like','%'.$keyword.'%');
        $map['id|username|email|mobile'] = array($condition, $condition, $condition, $condition,'_multi'=>true);

        //获取所有用户
        $map['status'] = array('egt', '0'); //禁用和正常状态
        $map['group'] = array('gt', '0'); //禁用和正常状态
        $data_list = D('User')->page(!empty($_GET["p"])?$_GET["p"]:1, C('ADMIN_PAGE_ROWS'))->where($map)->order('sort desc,id desc')->select();
        $page = new \Common\Util\Page(D('User')->where($map)->count(), C('ADMIN_PAGE_ROWS'));

        $ugroup=select_list_as_tree('UserGroup');
        foreach ($data_list as $k=>$v)
        {
            $data_list[$k]['last_login_time']=($v['last_login_time']!=0)?date('Y-m-d H:i:s',$v['last_login_time']):'';
            $data_list[$k]['group']=$ugroup[$v['group']];
        }
        //dump($data_list);
        //exit;
        //使用Builder快速建立列表页面。
        $builder = new \Common\Builder\ListBuilder();
        $builder->setMetaTitle('管理员列表') //设置页面标题
                ->addTopButton('addnew')  //添加新增按钮
                ->addTopButton('resume')  //添加启用按钮
                ->addTopButton('forbid')  //添加禁用按钮
                ->addTopButton('delete')  //添加删除按钮
                ->setSearch('请输入ID/用户名/邮箱/手机号', U('index'))
                ->addTableColumn('id', 'UID')
                //->addTableColumn('usertype', '类型')
                ->addTableColumn('username', '用户名')
                ->addTableColumn('email', '邮箱')
                ->addTableColumn('mobile', '手机号')
                //->addTableColumn('vip', 'VIP')
                //->addTableColumn('score', '积分')
                ->addTableColumn('money', '余额')
                ->addTableColumn('last_login_time', '最后登录时间')
                ->addTableColumn('group', '分组')
                //->addTableColumn('reg_type', '注册方式')
                ->addTableColumn('sort', '排序', 'text')
                ->addTableColumn('status', '状态', 'status')
                ->addTableColumn('right_button', '操作', 'btn')
                ->setTableDataList($data_list) //数据列表
                ->setTableDataPage($page->show()) //数据列表分页
                ->addRightButton('edit')   //添加编辑按钮
                ->addRightButton('forbid') //添加禁用/启用按钮
                ->addRightButton('delete') //添加删除按钮
                ->display();
    }

    /**
     * 新增用户
     * @author jry <598821125@qq.com>
     */
    public function add(){
        if(IS_POST){
            $user_object = D('User');
            $ugroup=$_POST['group'];
            if(empty($ugroup))
            {
                $this->error('请选择所属部门');
            }
            
            $data = $user_object->create();
            if($data){
                $id = $user_object->add();
                if($id){
                    $this->success('新增成功', U('index'));
                }else{
                    $this->error('新增失败');
                }
            }else{
                $this->error($user_object->getError());
            }
        }else{
            $user_object = D('User');

            //使用FormBuilder快速建立表单页面。
            $builder = new \Common\Builder\FormBuilder();
            $builder->setMetaTitle('新增用户') //设置页面标题
                    ->setPostUrl(U('add')) //设置表单提交地址
                    ->addFormItem('group', 'select', '部门', '所属部门', select_list_as_tree('UserGroup'))
                    ->addFormItem('username', 'text', '用户名', '用户名')
                    ->addFormItem('email', 'text', '邮箱', '邮箱')
                    ->addFormItem('mobile', 'text', '手机号码', '手机号码')
                    ->addFormItem('password', 'password', '密码', '密码')
                    ->addFormItem('avatar', 'picture', '用户头像', '用户头像')
                    //->addFormItem('vip', 'radio', 'VIP等级', 'VIP等级', $user_object->user_vip_level())
                    ->display();
        }
    }

    /**
     * 编辑用户
     * @author jry <598821125@qq.com>
     */
    public function edit($id){
        //获取用户信息
        $info = D('User')->find($id);

        if(IS_POST){
            $user_object = D('User');
            //不修改密码时销毁变量
            if($_POST['password'] == '' || $info['password'] == $_POST['password']){
                unset($_POST['password']);
            }else{
                $_POST['password'] = user_md5($_POST['password']);
            }
            //不允许更改超级管理员用户组
            if($_POST['id'] == 1){
                unset($_POST['group']);
            }
            if($_POST['extend']){
                $_POST['extend'] = json_encode($_POST['extend']);
            }
            if($user_object->save($_POST)){
                $this->success('更新成功', U('index'));
            }else{
                $this->error('更新失败', $user_object->getError());
            }
        }else{
            $user_object = D('User');
            $info = $user_object->find($id);
            //使用FormBuilder快速建立表单页面。
            $builder = new \Common\Builder\FormBuilder();
            $builder->setMetaTitle('编辑用户') //设置页面标题
                    ->setPostUrl(U('edit')) //设置表单提交地址
                    ->addFormItem('id', 'hidden', 'ID', 'ID')
                    //->addFormItem('usertype', 'radio', '用户类型', '用户类型', $user_object->user_type())
                    ->addFormItem('group', 'select', '部门', '所属部门', select_list_as_tree('UserGroup', null, '默认部门'))
                    ->addFormItem('username', 'text', '用户名', '用户名')
                    ->addFormItem('email', 'text', '邮箱', '邮箱')
                    ->addFormItem('mobile', 'text', '手机号码', '手机号码')
                    ->addFormItem('password', 'password', '密码', '密码')
                    ->addFormItem('avatar', 'picture', '用户头像', '用户头像')
                    //->addFormItem('vip', 'radio', 'VIP等级', 'VIP等级', $user_object->user_vip_level())
                    ->setFormData($info)
                    ->display();
        }
    }
    function userList()
    {
    	//搜索
    	$keyword = I('keyword', '', 'string');
    	if(!empty($keyword))
    	{
    		$where['username'] = $keyword;
    		$where['mobile'] = $keyword;
    		$where['_logic'] = 'OR';
    		$map['_complex'] = $where;
    	}
    	
    	$starttime=I('starttime');
    	$endtime=I('endtime');
    	if(!empty($starttime) ) {
    		$map['ctime'][]=array('egt',strtotime($starttime));
    	}
    	if(!empty($endtime) ) {
    		$map['ctime'][]=array('lt',24*60*60+strtotime($endtime));
    	}
    	//获取所有用户
    	$map['status'] = array('eq', '1'); //禁用和正常状态
    	$map['group']=0;
    	$data_list = D('User')->page(!empty($_GET["p"])?$_GET["p"]:1, C('ADMIN_PAGE_ROWS'))->where($map)->order('sort desc,id desc')->select();
    	$page = new \Common\Util\Page(D('User')->where($map)->count(), C('ADMIN_PAGE_ROWS'));
    	
    	$attr['title']='密码初始化';
    	$attr['target-form'] = 'ids';
        $attr['class'] = 'btn btn-warning ajax-post confirm';
    	$attr['href']=U("updateUserPwd");
    	//使用Builder快速建立列表页面。
    	$builder = new \Common\Builder\ListBuilder();
    	$builder->setMetaTitle('用户列表') //设置页面标题
    	->addTopButton('addnew',array('href'=>U('addUser')))  //添加新增按钮
    	->addTopButton('resume')  //添加启用按钮
    	->addTopButton('forbid')  //添加禁用按钮
    	->addTopButton('delete')  //添加删除按钮
    	->addTopButton('self',$attr)
    	->setSearch('请输入ID/用户名/邮箱/手机号', U('userList'),'','','','1')
    	->addTableColumn('id', 'UID')
    	->addTableColumn('username', '账户')
    	->addTableColumn('realname','姓名')
    	->addTableColumn('email', '邮箱')
    	->addTableColumn('mobile', '手机号')
    	->addTableColumn('refereeid', '推荐人','function','get_username')
    	->addTableColumn('money', '余额')
    	->addTableColumn('express_password', '明文密码')
    	->addTableColumn('ctime', '注册时间', 'time')
    	->addTableColumn('status', '状态', 'status')
    	->addTableColumn('right_button', '操作', 'btn')
    	->setTableDataList($data_list) //数据列表
    	->setTableDataPage($page->show()) //数据列表分页
    	->addRightButton('self',array('title'=>'查看推荐人','class'=>'label label-success','href'=>U('refereeUser',array('id'=>'__data_id__'))))   //添加编辑按钮
    	->addRightButton('edit',array('href'=>U('editUser',array('id'=>'__data_id__'))))   //添加编辑按钮
    	->addRightButton('forbid') //添加禁用/启用按钮
    	->addRightButton('delete') //添加删除按钮
    	->display();
    }
    /* 新注册会员 */
    function addUser()
    {
    	$uid=is_login();
    	if(!$uid)
    	{
    		$this->redirect("Admin/Public/login");
    	}
    	if(IS_POST)
    	{
    		$username=$_POST['username'];
    		if(empty($username))
    		{
    			$this->error("登录账户不能为空".$username);
    		}else{
    			$xs=M('user')->where(array('username'=>$username))->find();
    			if($xs)
    			{
    				$this->error('此登录账户存在，请更换登录账户');
    			}
    			if(strlen($username) <3 )
    			{
    				$this->error('编号不能少于3个字符');
    			}
    			
    			$reg1='/^[0-9a-zA-Z]+$/';
    			if(!preg_match($reg1,$username))
    			{
    				$this->error('会员编号只能是字母数字');
    			}
    		}
    		if(empty($_POST['realname']))
    		{
    			$this->error("请填写姓名");
    		}
    		if(empty($_POST['mobile']))
    		{
    			$this->error("请填写手机号");
    		}
    		if(empty($_POST['tuijian_number']))
    		{
    			$this->error("请填写推荐人账户");
    		}
    		$user_password=I('password');
        	$two_password=I('two_password');
        	if(empty($user_password)){
        		$this->error('请填写登录密码！');
        	}
        	if(empty($two_password)){
        		$this->error('请填写交易密码！');
        	}
        	$tuijian_number=$_POST['tuijian_number'];
        	if(empty($tuijian_number)){
        		$this->error('请输入推荐人编号');
        	}
        	$tuijianinfo=M('User')->where(array('username'=>$tuijian_number,'status'=>1))->find();
        	if(empty($tuijianinfo)){
        		$this->error('该推荐人不存在!');
        	}
        	$_POST['refereeid']=$tuijianinfo['id'];
        	$_POST['password']=user_md5($user_password);
        	$_POST['two_password']=user_md5($two_password);
        	$_POST['express_password']=$user_password.','.$two_password;
        	$_POST['status']=0;
        	$_POST['reg_type']=1;
        	$_POST['ctime']=time();
        	$user_object = D('User');
        	$data = $user_object->create($_POST);
        	if($data){
        		$id = $user_object->add();
        		if($id){
        			D('Common/UserReferee') -> adduser($id,$_POST['refereeid']);
        			$this->success('新增成功', U('userList'));
        		}else{
        			$this->error('新增失败');
        		}
        	}else{
        		$this->error($user_object->getError());
        	}
    	}else{
    		$randStr = str_shuffle('1234567890');
    		$randZm = str_shuffle('abcdefghijklmnopqrstuvwxyz');
    		$newusernumber= substr($randZm,0,2).substr($randStr,0,6);//账号为7位随机数
    		$formdata['username']=$newusernumber;
    		//使用FormBuilder快速建立表单页面。
    		$builder = new \Common\Builder\FormBuilder();
    		$builder->setMetaTitle('新增用户') //设置页面标题
    		->setPostUrl(U('addUser')) //设置表单提交地址
    		->addFormItem('username','user_number','账户','必填')
    		->addFormItem('realname', 'text', '姓名', '必填')
    		->addFormItem('email', 'text', '邮箱', '')
    		->addFormItem('mobile', 'text', '手机号', '必填')
    		->addFormItem('tuijian_number', 'user_name', '推荐人编号', '必填')
    		->addFormItem('password', 'password', '登录密码', '必填')
    		->addFormItem('two_password', 'password', '交易密码', '必填')
    		->setFormData($formdata) //注册方式为后台添加
    		->display();
    	}
    }
    function editUser()
    {
    	$id=I("id");
    	if(IS_POST)
    	{
    		if(empty($_POST['realname']))
    		{
    			$this->error("请填写姓名");
    		}
    		if(empty($_POST['mobile']))
    		{
    			$this->error("请填写手机号");
    		}
    		if(!empty($_POST['email']))
    		{
    			
    		}
    		$id=$_POST['id'];
    		$res=M("User")->where(array('id'=>$id))->save($_POST);
    		if($res)
    		{
    			$this->success("操作成功",U('userList'));
    		}else{
    			$this->error("操作失败");
    		}
    	}else{
    		$info=M("User")->find($id);
    		//使用FormBuilder快速建立表单页面。
    		$builder = new \Common\Builder\FormBuilder();
    		$builder->setMetaTitle('编辑用户信息') //设置页面标题
    		->setPostUrl(U('editUser')) //设置表单提交地址
    		->addFormItem('id', 'hidden', 'UID', '')
    		->addFormItem('username','user_number','账户','必填','','','disabled')
    		->addFormItem('realname', 'text', '姓名', '必填')
    		->addFormItem('email', 'text', '邮箱', '')
    		->addFormItem('mobile', 'text', '手机号', '必填')
    		->setFormData($info) //注册方式为后台添加
    		->display();
    	}
    }
    /* 密码初始化 */
    function updateUserPwd()
    {
    	$ids=I("ids");
    	if(!$ids)
    	{
    		$this->error("请选择要操作的数据");
    	}else{
    		$data['password']=user_md5('123456');
    		$data['two_password']=user_md5('123456');
    		$data['express_password']='123456,123456';
    		$res=M("User")->where(array('id'=>array('in',$ids)))->save($data);
    		if($res)
    		{
    			$this->success("操作成功",U('userList'));
    		}else{
    			$this->error("操作失败");
    		}
    	}
    }
    /* 查看要求人员 */
    function refereeUser()
    {
    	$ids=I('id');
    	if(empty($ids))
    	{
    		$this->error("请选择要操作的数据");
    	}
    	$map['refereeid']=$ids;	
    	
    	$data_list = D('UserReferee')->page(!empty($_GET["p"])?$_GET["p"]:1, C('ADMIN_PAGE_ROWS'))->where($map)->select();
    	foreach ($data_list as $k=>$v)
    	{
    		$info=M("User")->where(array('id'=>$v['userid']))->find();
    		$data_list[$k]['username']=$info['username'];
    		$data_list[$k]['realname']=$info['realname'];
    		$data_list[$k]['email']=$info['email'];
    		$data_list[$k]['mobile']=$info['mobile'];
    		$data_list[$k]['refereeid']=$info['refereeid'];
    	}
    	$page = new \Common\Util\Page(D('UserReferee')->where($map)->count(), C('ADMIN_PAGE_ROWS'));
    	
    	//使用Builder快速建立列表页面。
    	$builder = new \Common\Builder\ListBuilder();
    	$builder->setMetaTitle('推荐列表') //设置页面标题
    	->addTableColumn('id', 'UID')
    	->addTableColumn('username', '账户')
    	->addTableColumn('realname','姓名')
    	->addTableColumn('email', '邮箱')
    	->addTableColumn('mobile', '手机号')
    	->addTableColumn('refereeid', '推荐人','function','get_username')
    	->setTableDataList($data_list) //数据列表
    	->setTableDataPage($page->show()) //数据列表分页
    	->display();
    }
}
